package org.springmole.business.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springmole.business.bean.DbConnection;
import org.springmole.business.bean.DbConnectionResultData;
import org.springmole.business.bean.QueryRequest;
import org.springmole.business.bean.Result;
import org.springmole.business.bean.ResultData;
import org.springmole.business.bean.SchemaResultData;
import org.springmole.business.dao.SpringMoleDao;
import org.springmole.business.dao.impl.AbstractSpringMoleDaoImpl;
import org.springmole.business.service.SpringMoleService;
import org.springmole.common.GeneralXMLException;
import org.springmole.common.service.GeneralXMLService;
import org.w3c.dom.Document;


@Service
public class SpringMoleServiceImpl implements SpringMoleService {
		
	@Autowired
	private ApplicationContext applicationContext;
	
	@Autowired
	private GeneralXMLService generalXMLService;
	
	private Document document = null;
	
	
	@Override
	public Result<DbConnectionResultData> openDbConnection(DbConnection dbConnection) {
		Result<DbConnectionResultData> result = new Result<DbConnectionResultData>();
		
		String url = dbConnection.getUrl();
		if (url == null || url.equals("") || !url.contains(":")) {
			result.getResultStatus().setMessage("Invalid connectio URL: " + url);
			return result;
		}
		
		try {
			SpringMoleDao springMoleDao = getSpringMoleDao(dbConnection.getUrl());
			return springMoleDao.openDbConnection(dbConnection);
		} catch (Exception e) {
			result.getResultStatus().parseException(e);
			return result;
		}
	}


	@Override
	public Result<SchemaResultData> openSchema(DbConnection dbConnection, String schemaName) {
		try {
			SpringMoleDao springMoleDao = getSpringMoleDao(dbConnection.getUrl());
			return springMoleDao.openSchema(dbConnection, schemaName);
		} catch (Exception e) {	
			return new Result<SchemaResultData>(e);
		}
	}
	
	
	@Override
	public Result<? extends ResultData> executeQuery(QueryRequest queryRequest) throws GeneralXMLException {
		if (document == null) {
			document = generalXMLService.createDocument();
		}
		SpringMoleDao springMoleDao = getSpringMoleDao(queryRequest.getUrl()); 
		return springMoleDao.executeQuery(queryRequest, document);
	}
	
	
	private SpringMoleDao getSpringMoleDao(String url) {
		String jdbcName = url.split(":")[1];
		return (SpringMoleDao)applicationContext.getBean(AbstractSpringMoleDaoImpl.IMPLEMENTATION_BEAN_NAME_PREFIX + jdbcName);
	}
	
}
